package com.itheima.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.OrderMP;
import com.itheima.health.pojo.OrderSettingMP;
import com.itheima.health.pojo.SetmealMP;
import com.itheima.health.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/mobile/order")
public class MobileOrderController {

    @Autowired
    private SetmealServiceMP setmealService;

    @Autowired
    private MemberService memberService1;

    @Autowired
    private OrderServiceMP orderService;

    @Autowired
    private OrderSettingServiceMP orderSettingService;

    @Autowired
    private SmsService smsService;

    @PostMapping("/submit")
    public Result save(@RequestBody Map<String, String> params) throws ParseException {
        log.info("[接收数据] params = {}", params);

        //确认验证码
        if (!smsService.checkValidateCode("ORDER", params.get("telephone"), params.get("validateCode"))) {
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }

        //会员是否存在
        Member member = new Member();
        LambdaQueryWrapper<Member> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(Member::getIdCard, params.get("idCard"));
        Member hasMember = memberService1.getOne(memberWrapper);
        if (hasMember == null) {
            //自动注册为会员
            member.setName(params.get("name"));
            member.setSex(params.get("sex"));
            member.setIdCard(params.get("idCard"));
            member.setPhoneNumber(params.get("telephone"));
            member.setRegTime(new Date());
            memberService1.save(member);
        } else {
            member = hasMember;
        }
        log.info("[会员数据] member = {}", member);

        //选择的日期下，有没有安排预约
        LambdaQueryWrapper<OrderSettingMP> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderSettingMP::getOrderDate, params.get("orderDate"));
        OrderSettingMP orderSetting = orderSettingService.getOne(wrapper);
        //初始化订单
        OrderMP order = new OrderMP();
        //可以进行预约
        if (orderSetting != null) {
            //已经满员
            if (orderSetting.getReservations() >= orderSetting.getNumber()) {
                return new Result(false, MessageConst.ORDER_FULL);
            }
            //是否已经预约过了
            LambdaQueryWrapper<OrderMP> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderMP::getMemberId, member.getId());
            queryWrapper.eq(OrderMP::getOrderDate, params.get("orderDate"));
            OrderMP hasOrder = orderService.getOne(queryWrapper);
            //没有预约过
            if (hasOrder == null) {
                //生成订单信息
                order.setMemberId(member.getId());
                order.setOrderDate(new SimpleDateFormat("yyyy-MM-dd").parse(params.get("orderDate")));
                order.setOrderType(OrderMP.ORDERTYPE_WEIXIN);
                order.setOrderStatus(OrderMP.ORDERSTATUS_NO);
                order.setSetmealId(Integer.parseInt(params.get("setmealId")));
            } else {
                //已经预约了
                return new Result(false, MessageConst.HAS_ORDERED);
            }
        } else {
            //不可以进行预约
            return new Result(false, MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        log.info("[订单数据] order = {}", order);

        //保存订单信息
        orderService.save(order);
        //已预约人数 +1
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingService.updateById(orderSetting);
        return new Result(true, MessageConst.ORDER_SUCCESS, order);
    }

    @GetMapping("/findById")
    public Result findById(Integer id) {
        LambdaQueryWrapper<OrderMP> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(OrderMP::getId, id);
        OrderMP order = orderService.getOne(orderWrapper);
        if (order != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("orderType", order.getOrderType());
            map.put("orderDate", new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate()));

            LambdaQueryWrapper<Member> memberWrapper = new LambdaQueryWrapper<>();
            memberWrapper.eq(Member::getId, order.getMemberId());
            Member member = memberService1.getOne(memberWrapper);
            map.put("member", member.getName());

            LambdaQueryWrapper<SetmealMP> setmealWrapper = new LambdaQueryWrapper<>();
            setmealWrapper.eq(SetmealMP::getId, order.getSetmealId());
            SetmealMP setmeal = setmealService.getOne(setmealWrapper);
            map.put("setmeal", setmeal.getName());

            return new Result(true, MessageConst.QUERY_ORDER_SUCCESS, map);
        } else {
            return new Result(false, MessageConst.QUERY_ORDER_FAIL);
        }
    }
}
